import axios, { AxiosResponse } from 'axios'
import { Log } from '~/utils'
import TranslateEngine, { TranslateOptions, TranslateResult } from './base'
import { workspace, WorkspaceConfiguration } from 'vscode'


const apiKey = 'app-qL2lh3mIVEtOQzZ4PA4Yh5uu'
const timeout = 30000
const difyAi = axios.create({
  baseURL: 'http://120.77.133.46:8007/v1',
  headers: {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
  },
  timeout,
})

difyAi.interceptors.request.use((req) => {
  Log.info(`[Dify] Request data:${JSON.stringify(req.data)}`)
  return req
})

difyAi.interceptors.response.use((res) => {
  Log.info(`[Dify] Response:${res.status},${JSON.stringify(res.data)}`)
  return res
})


class DifyTranslateEngine extends TranslateEngine {

    async translate(options: TranslateOptions): Promise<TranslateResult> {
      const {
        text,
        from = 'auto',
        to = 'en'
      } = options;
      // 提取翻译结果Res
      let translatedRes = '';
      const config: WorkspaceConfiguration = workspace.getConfiguration('i18n-ally');

      Log.info(`[Dify] Starting translation: from=${from}, to=${to}, textLength=${text.length}, sourceType=${config.get('sourceType', 'ALL')}`);

      try {
        // 验证必要参数
        if (!apiKey) {
          throw new Error('API key is required');
        }

        // 调用 Dify API
        const url = 'http://120.77.133.46:8007/v1/workflows/run';
        Log.info(`[Dify] API endpoint: ${url}`);

        const response = await difyAi.post('/workflows/run', {
            inputs: {
              source_text: text,
              source_lang: from,
              target_lang: to,
              source_type: config.get('sourceType', 'ALL')
            },
            response_mode: 'streaming',
            user: 'dify-translate-engine'
          },
        )

        const chunk = response.data as string;
        try {
          // 解析SSE格式数据流
          const lines = chunk.split('\n').filter((line) => line.trim() !== '');
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const dataStr = line.slice(5).trim(); // 移除 'data: ' 前缀
              if (!dataStr) continue;
              try {
                // 尝试解析JSON数据
                const data = JSON.parse(dataStr);
                // console.log("🚀 ~ handleTranslate ~ data:", data)
                if (data.event === 'node_finished' && data.data?.node_type === 'end') {
                  // 处理翻译结果
                  const translatedText = data.data?.outputs?.text;
                  if (translatedText) translatedRes += translatedText;
                }
              } catch (e) {
                // 如果是纯文本数据，直接追加
                if (dataStr.includes('translated_text') || dataStr.includes('text_list')) {
                  translatedRes += dataStr;
                }
              }
            }
          }
        } catch (e) {
          // 如果解析失败，直接追加原始数据
          translatedRes += chunk;
        }

        return {
          text,
          from,
          to,
          response: null,
          linkToResult: '',
          result: [translatedRes],
          detailed: [translatedRes]
        };

      } catch (error) {
        Log.error(`[Dify] Translation error: ${error}`);

        return {
          text,
          from,
          to,
          response: null,
          linkToResult: '',
          error: error as Error,
          result: [],
          detailed: []
        };
      }
    }

    /**
     * 批量翻译文本
     * @param texts 要翻译的文本数组
     * @param from 源语言代码
     * @param to 目标语言代码
     * @returns 翻译结果数组
     */
    async translateBatch(
      texts: string[],
      from?: string,
      to?: string
    ): Promise<TranslateResult[]> {
      const results: TranslateResult[] = [];

      Log.info(`[Dify] Starting batch translation of ${texts.length} texts`);

      for (const text of texts) {
        const result = await this.translate({ text, from, to });
        results.push(result);

        // 添加延迟以避免速率限制
        await new Promise(resolve => setTimeout(resolve, 100));
      }

      Log.info('[Dify] Batch translation completed');

      return results;
    }
}

export default DifyTranslateEngine
